package com.lemurian.bankdata.action.business;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.interceptor.validation.SkipValidation;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.ApplicationCategory;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.services.CategoryService;
import com.lemurian.bankdata.services.ClientCertificateService;
import com.lemurian.bankdata.services.ClientDocumentService;
import com.lemurian.bankdata.services.ClientService;
import com.lemurian.bankdata.services.ManagementClientTypeService;
import com.lemurian.bankdata.services.ManagementService;
import com.lemurian.bankdata.services.SignatureScheduleService;
import com.lemurian.bankdata.services.TaxService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.Category;
import com.lemurian.entity.Client;
import com.lemurian.entity.ClientCertificate;
import com.lemurian.entity.ClientDocument;
import com.lemurian.entity.Management;
import com.lemurian.entity.ManagementClientType;
import com.lemurian.entity.SignatureSchedule;
import com.lemurian.entity.Tax;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("serial")
public class DetailKlienAction extends BaseAction implements Preparable {

	private BankDataLogger log = BankDataLogger.getLogger(DetailKlienAction.class.getSimpleName());
	
	private Client klien = new Client();
	private List<Client> listKlien = new ArrayList<Client>();
	
	private Management kepengurusan = new Management();
	private List<Management> listKepengurusan = new ArrayList<Management>();
	
	private int id = 0;
	private String prev = "";
	
	private int departmentId;
	private List<Category> listTipeDepartemen;
	
	private String namaSertifikat = "";
	private String noSertifikat = "";
	private String wilayahSertifikat = "";
	private String accountOfficer = "";	
	private String bankName = "";
	
	private String namaPembeli = "";
	private String namaPenjual = "";
	private String petugasKetik = "";
	private String lokasiDokumen = "";
	
	private String nominalPajakSSB = "";
	private String nominalPajakSSP = "";
	private String tanggalPembayaran = "";
	
	private String tglTTD = "";
	private String jamTTD = "";
	private String tempatTTD = "";
	
	private int isNotaris = 1;
	private int isPPAT = 1;
	
	private List<ClientCertificate> listAktaKlienPPAT = new ArrayList<ClientCertificate>();
	private List<ClientCertificate> listAktaKlienNotaris = new ArrayList<ClientCertificate>();
	
	private List<ManagementClientType> listKepengurusanKlienPPAT = new ArrayList<ManagementClientType>();
	private List<ManagementClientType> listKepengurusanKlienNotaris = new ArrayList<ManagementClientType>();
	
	private List<ClientDocument> listDokumenKlien = new ArrayList<ClientDocument>();
	
	private User user;
	private BankDataPrincipal principal;
	
	private NumberFormat nf = NumberFormat.getInstance();
	private DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
	private DateFormat dateonly = new SimpleDateFormat("dd-MMMM-yyyy");
	private DateFormat dateonly2 = new SimpleDateFormat("dd-MM-yyyy");
	private DateFormat timeonly = new SimpleDateFormat("HH:mm");
	
	@Autowired private ClientService clientService;
	@Autowired private TaxService taxService;
	@Autowired private SignatureScheduleService signatureScheduleService;
	@Autowired private ManagementService kepengurusanService;
	
	@Autowired private CategoryService categoryService;
	@Autowired private ClientCertificateService aktaKlienService;
	@Autowired private ManagementClientTypeService kepengurusanKlienService;
	@Autowired private ClientDocumentService dokumenKlienService;

	private String tglCekOK;

	private String pendingRemarks;
	
	@Override
	public void prepare() throws Exception {
		try {
			log.info(": : : : : ON DETAIL KLIEN ");
			
			principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
			user = principal.getUser();
			
			log.sInfo("get client id [%s]", id);
	        if (id > 0) {
	        	klien = clientService.load(id);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	@SkipValidation
	public String list() {
		log.info("list Klien yang masuk");
		try {
			PartialList<Client> partialList = clientService.findAllClientInformation(getStart(), getCount(), 
					getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "createDate") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "createDate"),
					departmentId != 0 ? Restrictions.eq("department.id", departmentId) : Restrictions.ne("id", new Integer(-1)),
					namaSertifikat != null && namaSertifikat.length() > 0 ? Restrictions.ilike("certificate.name", namaSertifikat, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					noSertifikat != null && noSertifikat.length() > 0 ? Restrictions.eq("certificate.number", noSertifikat) : Restrictions.ne("id", new Integer(-1)),
					wilayahSertifikat != null && wilayahSertifikat.length() > 0 ? Restrictions.ilike("certificate.reqion", wilayahSertifikat, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					accountOfficer != null && accountOfficer.length() > 0 ? Restrictions.ilike("accountOfficer.loginId", accountOfficer, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					bankName != null && bankName.length() > 0 ? Restrictions.ilike("bank.name", bankName, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					namaPembeli != null && namaPembeli.length() > 0 ? Restrictions.ilike("debitur.name", namaPembeli, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					namaPenjual != null && namaPenjual.length() > 0 ? Restrictions.ilike("seller.name", namaPenjual, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					petugasKetik != null && petugasKetik.length() > 0 ? Restrictions.ilike("officerType.loginId", petugasKetik, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					lokasiDokumen != null && lokasiDokumen.length() > 0 ? Restrictions.ilike("documentLocation", lokasiDokumen, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1))
					);
			
			listKlien = partialList.getList();
			log.sInfo("found total list of klien [%s]", listKlien.size());
			
	        setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
	        setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));
	
	        partialList = null;
	        
	        listTipeDepartemen = categoryService.findByCriteria(Order.asc("id"),(Restrictions.eq("parent.id", ApplicationCategory.TIPE_DEPARTEMEN.code())));
	    	log.sInfo("found listTipeDepartemen [%s]", listTipeDepartemen.size());
	          
		} catch (Exception e) {
			e.printStackTrace();
		}
	    setMappedRequest(GeneralConstant.LIST);
	    return SUCCESS;
	}
	
	@Override
	@SkipValidation
	public String detail() {
		try {
			System.out.println("prev : " + prev);
			setPreviousPage(prev);
			
			if (user.getDepartment() == null) {
				isNotaris = 1;
				isPPAT = 1;
			} else if (user.getDepartment().getId() == ApplicationCategory.DEPARTEMEN_PPAT.code()) {
				isNotaris = 0;
			} else if (user.getDepartment().getId() == ApplicationCategory.DEPARTEMEN_NOTARIS.code()) {
				isPPAT = 0;
			}
			
			// PAJAK
			Tax tax= taxService.findTaxByClient(klien);
			if (tax != null && tax.getId() > 0) {
    			log.sInfo("found tax nominal SSB for this client [%s]", tax.getNominalSSB());
    			log.sInfo("found tax nominal SSP for this client [%s]", tax.getNominalSSP());
    			
    			if (tax.getNominalSSB() != null) {
    				nominalPajakSSB = nf.format(tax.getNominalSSB());	
				}
    			if (tax.getNominalSSP() != null) {
    				nominalPajakSSP = nf.format(tax.getNominalSSP());	
				}
    			
		    	if (tax.getPaymentDate() != null) {
					tanggalPembayaran = dateonly.format(tax.getPaymentDate());	
				}
			}
			
			// JADWAL TANDA TANGAN
			SignatureSchedule signatureSchedule = signatureScheduleService.findSignatureScheduleByClient(klien);
			if (signatureSchedule != null && signatureSchedule.getId() > 0) {
				if (signatureSchedule.getSignatureDate() != null) {
	    			log.sInfo("found jadwal ttd [%s]", signatureSchedule.getSignatureDate());
	    			tglTTD = dateonly.format(signatureSchedule.getSignatureDate());
	    			jamTTD = timeonly.format(signatureSchedule.getSignatureDate());
				}
    			tempatTTD = signatureSchedule.getPlace();
			}
			
			// KEPENGURUSAN
			listKepengurusan = kepengurusanService.findByCriteria(Order.asc("debitur.name"), Restrictions.eq("client", klien));
			log.sInfo("found total kepengurusan for this client : [%s]", listKepengurusan.size());
			/*if (kepengurusan != null && kepengurusan.getId() > 0) {
				log.sInfo("found kepengurusan for klien [%s]", kepengurusan.getClient().getDebitur().getName());
			}*/
			
			// LIST AKTA & KEPENGURUSAN
			if (klien.getDepartment() != null) {
				log.info("klien dept id : " + klien.getDepartment().getId());
				if (klien.getDepartment().getId() != ApplicationCategory.DEPARTEMEN_NOTARIS.code()) {
					listAktaKlienPPAT = aktaKlienService.findByCriteria(Order.asc("certificateType.name"), Restrictions.eq("client", klien), Restrictions.eq("certificateType.parent.id", ApplicationCategory.AKTA_PPAT.code()));
					log.sInfo("found akta klien %s", listAktaKlienPPAT.size());
					
					listKepengurusanKlienPPAT = kepengurusanKlienService.findByCriteria(Order.asc("managementType.name"), Restrictions.eq("client", klien), Restrictions.eq("managementType.parent.id", ApplicationCategory.KEPENGURUSAN_PPAT.code()));
					log.sInfo("found kepengurusan klien %s", listKepengurusanKlienPPAT.size());
				}
				
				if (klien.getDepartment().getId() != ApplicationCategory.DEPARTEMEN_PPAT.code()) {
					listAktaKlienNotaris = aktaKlienService.findByCriteria(Order.asc("certificateType.name"), Restrictions.eq("client", klien), Restrictions.eq("certificateType.parent.id", ApplicationCategory.AKTA_NOTARIS.code()));
					log.sInfo("found akta klien %s", listAktaKlienNotaris.size());
					
					listKepengurusanKlienNotaris = kepengurusanKlienService.findByCriteria(Order.asc("managementType.name"), Restrictions.eq("client", klien), Restrictions.eq("managementType.parent.id", ApplicationCategory.KEPENGURUSAN_NOTARIS.code()));
					log.sInfo("found kepengurusan klien %s", listKepengurusanKlienNotaris.size());
				}
			}
			
			// LIST JENIS DOKUMEN
			listDokumenKlien = dokumenKlienService.findByCriteria(Order.asc("documentType.name"), Restrictions.eq("client", klien));
			log.sInfo("found dokumen klien %s", listDokumenKlien.size());
			
			if (prev.equalsIgnoreCase("PersetujuanKlienAction_list")) {
				setMappedRequestFullPath("PersetujuanKlienAction_save");
				if (klien.getCheckDate() != null) {
					tglCekOK = dateonly2.format(klien.getCheckDate());	
				} else {
					tglCekOK = "";
				}
					
				pendingRemarks = klien.getPendingRemarks();
			}
			return SUCCESS;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// ================================================================================================================================================
	@Override
	@SkipValidation
	public String add() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String save() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	@SkipValidation
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	@SkipValidation
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}
	

	public Client getKlien() {
		return klien;
	}
	public void setKlien(Client klien) {
		this.klien = klien;
	}
	public int getId() {
		return id;
	}
	public void setId(String id) {
		int id_ = 0;
		if(id != null && !id.equalsIgnoreCase("0")) {
			id = GlobalFunction.decodeParameter(id);
	        id_ = Integer.parseInt(id);
		}
        this.id = id_;
	}
	
	public String getNominalPajakSSB() {
		return nominalPajakSSB;
	}

	public void setNominalPajakSSB(String nominalPajakSSB) {
		this.nominalPajakSSB = nominalPajakSSB;
	}

	public String getNominalPajakSSP() {
		return nominalPajakSSP;
	}

	public void setNominalPajakSSP(String nominalPajakSSP) {
		this.nominalPajakSSP = nominalPajakSSP;
	}

	public String getTanggalPembayaran() {
		return tanggalPembayaran;
	}
	public void setTanggalPembayaran(String tanggalPembayaran) {
		this.tanggalPembayaran = tanggalPembayaran;
	}
	public String getTglTTD() {
		return tglTTD;
	}
	public void setTglTTD(String tglTTD) {
		this.tglTTD = tglTTD;
	}
	public String getJamTTD() {
		return jamTTD;
	}
	public void setJamTTD(String jamTTD) {
		this.jamTTD = jamTTD;
	}
	public String getTempatTTD() {
		return tempatTTD;
	}
	public void setTempatTTD(String tempatTTD) {
		this.tempatTTD = tempatTTD;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}


	public List<ClientCertificate> getListAktaKlienPPAT() {
		return listAktaKlienPPAT;
	}


	public void setListAktaKlienPPAT(List<ClientCertificate> listAktaKlienPPAT) {
		this.listAktaKlienPPAT = listAktaKlienPPAT;
	}


	public List<ClientCertificate> getListAktaKlienNotaris() {
		return listAktaKlienNotaris;
	}


	public void setListAktaKlienNotaris(List<ClientCertificate> listAktaKlienNotaris) {
		this.listAktaKlienNotaris = listAktaKlienNotaris;
	}


	public List<ManagementClientType> getListKepengurusanKlienPPAT() {
		return listKepengurusanKlienPPAT;
	}


	public void setListKepengurusanKlienPPAT(
			List<ManagementClientType> listKepengurusanKlienPPAT) {
		this.listKepengurusanKlienPPAT = listKepengurusanKlienPPAT;
	}


	public List<ManagementClientType> getListKepengurusanKlienNotaris() {
		return listKepengurusanKlienNotaris;
	}


	public void setListKepengurusanKlienNotaris(
			List<ManagementClientType> listKepengurusanKlienNotaris) {
		this.listKepengurusanKlienNotaris = listKepengurusanKlienNotaris;
	}


	public String getPrev() {
		return prev;
	}


	public void setPrev(String prev) {
		this.prev = prev;
	}

	public String getNamaSertifikat() {
		return namaSertifikat;
	}

	public void setNamaSertifikat(String namaSertifikat) {
		this.namaSertifikat = namaSertifikat;
	}

	public String getNoSertifikat() {
		return noSertifikat;
	}

	public void setNoSertifikat(String noSertifikat) {
		this.noSertifikat = noSertifikat;
	}

	public String getAccountOfficer() {
		return accountOfficer;
	}

	public void setAccountOfficer(String accountOfficer) {
		this.accountOfficer = accountOfficer;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getNamaPembeli() {
		return namaPembeli;
	}

	public void setNamaPembeli(String namaPembeli) {
		this.namaPembeli = namaPembeli;
	}

	public String getNamaPenjual() {
		return namaPenjual;
	}

	public void setNamaPenjual(String namaPenjual) {
		this.namaPenjual = namaPenjual;
	}

	public String getWilayahSertifikat() {
		return wilayahSertifikat;
	}

	public void setWilayahSertifikat(String wilayahSertifikat) {
		this.wilayahSertifikat = wilayahSertifikat;
	}

	public String getPetugasKetik() {
		return petugasKetik;
	}

	public void setPetugasKetik(String petugasKetik) {
		this.petugasKetik = petugasKetik;
	}

	public int getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(String departmentId) {
		int id_ = 0;
		if(departmentId != null && !departmentId.equalsIgnoreCase("0")) {
			departmentId = GlobalFunction.decodeParameter(departmentId);
	        id_ = Integer.parseInt(departmentId);
		}
        this.departmentId = id_;
	}

	public String getLokasiDokumen() {
		return lokasiDokumen;
	}

	public void setLokasiDokumen(String lokasiDokumen) {
		this.lokasiDokumen = lokasiDokumen;
	}

	public List<Client> getListKlien() {
		return listKlien;
	}

	public void setListKlien(List<Client> listKlien) {
		this.listKlien = listKlien;
	}

	public List<Category> getListTipeDepartemen() {
		return listTipeDepartemen;
	}

	public void setListTipeDepartemen(List<Category> listTipeDepartemen) {
		this.listTipeDepartemen = listTipeDepartemen;
	}

	public Management getKepengurusan() {
		return kepengurusan;
	}

	public void setKepengurusan(Management kepengurusan) {
		this.kepengurusan = kepengurusan;
	}

	public int getIsPPAT() {
		return isPPAT;
	}

	public void setIsPPAT(int isPPAT) {
		this.isPPAT = isPPAT;
	}

	public int getIsNotaris() {
		return isNotaris;
	}

	public void setIsNotaris(int isNotaris) {
		this.isNotaris = isNotaris;
	}

	public List<ClientDocument> getListDokumenKlien() {
		return listDokumenKlien;
	}

	public void setListDokumenKlien(List<ClientDocument> listDokumenKlien) {
		this.listDokumenKlien = listDokumenKlien;
	}

	public String getTglCekOK() {
		return tglCekOK;
	}

	public void setTglCekOK(String tglCekOK) {
		this.tglCekOK = tglCekOK;
	}

	public String getPendingRemarks() {
		return pendingRemarks;
	}

	public void setPendingRemarks(String pendingRemarks) {
		this.pendingRemarks = pendingRemarks;
	}

	public List<Management> getListKepengurusan() {
		return listKepengurusan;
	}

	public void setListKepengurusan(List<Management> listKepengurusan) {
		this.listKepengurusan = listKepengurusan;
	}
}
